require 'rubygems'
require 'bit-struct'

require 'milfs/object/interface'

module Mil
  module FS
    # Ruby representation of a binary structure using the BitStruct
    # library.
    #
    # ---
    # *Structure*:: <tt> </tt> 
    # +size+:: <tt>Size of the block list</tt>
    # +blocks+:: <tt>Variable length field containin an ordered list of Blocks</tt>
    class BlockListStruct < BitStruct
      float   :size,	  32,	  "Size of *data"
      rest    :blocks,		  "Ordered tab delimited list of blocks"
    end

    # A wrapper class to encapsulate the data structure BlockListStruct
    # and provide easy access to the structure.
    class BlockList < Mil::Object::Interface
      
      def initialize(list=nil)
	@struct = BlockListStruct.new

	self.blocks = list unless list.nil?
      end

      # This method will compare the internal wrapped structure with
      # that of the object passed in.
      def == (object)
	if ( truth = object.is_a? Mil::FS::BlockList )
	  truth |= @struct.size == object.struct.size
	  truth |= @struct.blocks == object.struct.blocks
	end

	truth
      end

      # This method returns a printable string representation 
      # of the wrapped Block structure.
      def dump
        "BlockList: #{@struct.blocks}"
      end

      # This method should be overriden to create an instance of the
      # wrapped structure type from the passed string and store it
      # in the @struct variable.
      def struct=(string)
	@struct = BlockListStruct.new(string)
      end

      # Store data_seg into the Block.
      def blocks=(list)
	raise ArgumentError, "expected Array, passed #{list.class}" unless list.is_a? Array

	if @struct
	  @struct.size = list.size
	  @struct.blocks = list.join('\t')
	else
	  @struct = BlockListStruct.new
	  @struct.size = list.size
	  @struct.blocks = list.join('\t')
	end
      end

      # Retrieve data from the Block.
      def blocks
	@struct.blocks.split('\t')
      end
    end
  end
end
